const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const cors = require('cors');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const mongoose = require('mongoose');
const winston = require('winston');
const path = require('path');
const dotenv = require('dotenv');

// 加载环境变量
dotenv.config();

// 导入路由
const authRoutes = require('./routes/auth');
const systemRoutes = require('./routes/system');
const fileRoutes = require('./routes/file');
const nginxRoutes = require('./routes/nginx');
const databaseRoutes = require('./routes/database');
const securityRoutes = require('./routes/security');
const taskRoutes = require('./routes/task');
const appRoutes = require('./routes/app');

// 导入中间件
const { verifyToken } = require('./middleware/auth');

// 初始化日志配置
const logger = winston.createLogger({
  level: process.env.LOG_LEVEL || 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
  ),
  transports: [
    new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
    new winston.transports.File({ filename: 'logs/combined.log' }),
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.colorize(),
        winston.format.simple()
      )
    })
  ]
});

// 初始化Express应用
const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: '*',
    methods: ['GET', 'POST']
  }
});

// 中间件配置
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(morgan('combined'));

// 健康检查端点
app.get('/api/health', (req, res) => {
  res.status(200).json({ status: 'ok', message: '服务器正常运行' });
});

// API路由
app.use('/api/auth', authRoutes);
app.use('/api/system', verifyToken, systemRoutes);
app.use('/api/file', verifyToken, fileRoutes);
app.use('/api/nginx', verifyToken, nginxRoutes);
app.use('/api/database', verifyToken, databaseRoutes);
app.use('/api/security', verifyToken, securityRoutes);
app.use('/api/task', verifyToken, taskRoutes);
app.use('/api/app', verifyToken, appRoutes);

// 404处理
app.use((req, res) => {
  res.status(404).json({ error: '请求的资源不存在' });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  logger.error(`${err.stack}`);
  res.status(500).json({ error: '服务器内部错误' });
});

// Socket.io 实时监控
const systemMonitor = require('./services/systemMonitor');
io.on('connection', (socket) => {
  logger.info(`客户端连接: ${socket.id}`);
  
  // 开始发送系统监控数据
  const monitorInterval = setInterval(async () => {
    try {
      const data = await systemMonitor.getSystemInfo();
      socket.emit('system-info', data);
    } catch (error) {
      logger.error(`监控数据获取失败: ${error.message}`);
    }
  }, 3000);
  
  socket.on('disconnect', () => {
    clearInterval(monitorInterval);
    logger.info(`客户端断开连接: ${socket.id}`);
  });
});

// 启动服务器函数
const startServer = () => {
  const PORT = process.env.PORT || 3000;
  server.listen(PORT, () => {
    logger.info(`服务器已启动，端口: ${PORT}`);
  });
};

// 检查是否使用MongoDB
const USE_MONGO = process.env.USE_MONGO !== 'false';

// 启动服务器
if (USE_MONGO) {
  mongoose.connect(process.env.MONGO_URI || 'mongodb://localhost:27017/linux-panel', {
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
    .then(() => {
      logger.info('MongoDB数据库连接成功');
      startServer();
    })
    .catch(err => {
      logger.error(`数据库连接失败: ${err.message}`);
      logger.info('以无数据库模式启动服务器');
      startServer();
    });
} else {
  logger.info('以无数据库模式启动服务器');
  startServer();
}

// 处理未捕获的异常
process.on('uncaughtException', (err) => {
  logger.error(`未捕获的异常: ${err.stack}`);
});

process.on('unhandledRejection', (reason, promise) => {
  logger.error(`未处理的Promise拒绝: ${reason}`);
}); 